/**
 * 资源库页面
 */
var DocumentPage = {
	flow: {},
	chooseList: [],
    /**
	 *	点击弹窗上传图片
	 *	点击查看详情，重新上传图片
	 *	重新上传的图片后缀必须和原文件保持一致 如原文件是png，新上传文件后缀也必须是png
	 */
	editFile : function(parentId, fileId) {
		var _that = this;
		layer.open({
			type: 2,
			title: '查看文件',
			shade: 0.4, //弹窗后边是否显示阴影 可以填true/false 或者0.？透明度
			shadeClose: false,//点击阴影是否关闭弹窗
			maxmin: true, //开启最大化最小化按钮
			closeBtn: 1, //不显示关闭按钮
			btn: ['确定','取消'],
			area: ["450px", "400px"],
			content: ctx + '/DocumentController/edit.do?fileId=' + (typeof fileId == 'undefined' ? "" : fileId) + "&parentId=" + parentId,
			yes: function(index){
         	   	_that.editFileSuccessCallback(index, parentId);
        	},
        	btn2: function(index) {
        		_that.editFileCancelCallback(index);
        	},
        	cancel: function(index) {
        		_that.editFileCancelCallback(index);
        	}
		});
	},
	/**
	 *  编辑、添加图片成功回调方法
	 */
	editFileSuccessCallback: function(index, parentId) {
		//当点击‘确定’按钮的时候，获取弹出层返回的值
	    var iframeWin = window["layui-layer-iframe" + index];
	    if (iframeWin.isLoading) {
			layer.msg("文件正在上传，不能进行操作");
		    return false;
	    }
	    var uploadRes = iframeWin.callbackdata();
	    //图片上传成功，添加数据库数据
 	   	if (typeof uploadRes != 'undefined' && uploadRes != null) {
			var url = ctx + "/DocumentController/addFileSave.do";
		    var params = uploadRes;
		    params.parentId = parentId;
		    var res = "";
		    Common.network(url, "POST", params, false, function(data) {
		    	res = data;
		    });
		    if (typeof res != 'undefined') {
                //最后关闭弹出层
                layer.close(index);
                if (res.result == "SUCCESS") {
						layer.msg("添加成功");
			    } else {
					layer.msg(res.message);
			    }
                setTimeout(function() {
                    query();
                }, 1000);
		    } else {
				layer.msg("添加失败，请稍后重试");
				//数据库添加失败，删除图片
				DocumentPage.cancelUpload(uploadRes);
		    }
 	   	}
	    layer.close(index);
	},
	/**
	 * 编辑、添加图片取消回调方法
	 */
	editFileCancelCallback: function(index) {
		var iframeWin = window["layui-layer-iframe" + index];
		//文件正在上传，阻止关闭窗口
		if (iframeWin.isLoading) {
			layer.msg("文件正在上传，不能关闭");
		    return false;
	    }
	    var uploadRes = iframeWin.callbackdata();
		//取消保存则删除文件
		if (typeof uploadRes != 'undefined' && uploadRes != null) {
    		DocumentPage.cancelUpload(uploadRes);
		}
		layer.close(index);
	},
	/**
	 *点击弹出添加文件夹弹窗页
	 */
	addFolder: function(parentId) {
		var _that = this;
		layer.open({
			type: 2,
			title: '添加文件夹',
			shade: 0.4, //弹窗后边是否显示阴影 可以填true/false 或者0.？透明度
			shadeClose: true,//点击阴影是否关闭弹窗
			maxmin: true, //开启最大化最小化按钮
			btn: ['确定','关闭'],
			area: ["450px", "300px"],
			content: ctx + '/DocumentController/addFolder.do',
			yes: function(index){
                _that.addFolderSuccessCallback(index, parentId);
            }
		});
	},
	addFolderSuccessCallback: function(index, parentId) {
		//当点击‘确定’按钮的时候，获取弹出层返回的值
	    var iframeWin = window["layui-layer-iframe" + index];
	    var validate = iframeWin.validate();
	    if (validate) {
			var res = iframeWin.callbackdata();
			var url = ctx + "/DocumentController/addFolderSave.do";
		    var params = res;
		    params.parentId = parentId;
		    var res = "";
		    Common.network(url, "POST", params, false, function(data) {
		    	res = data;
		    });
		    if (typeof res != 'undefined') {
                //最后关闭弹出层
                layer.close(index);
                if (res.result == "SUCCESS") {
					layer.msg("添加成功");
			    } else {
					layer.msg(res.message);
			    }
                setTimeout(function() {
                    query();
                }, 1000);
		    } else {
				layer.msg("添加失败，请稍后重试");
		    }
	    }
	},
	/**
	 *   放弃保存  删除已上传图片
	 */
	cancelUpload: function(uploadRes) {
		var url = ctx + "/UploadFileController/delete.do";
	    var params = {"path": uploadRes.path};
	    Common.network(url, "POST", params, false, function(data) {
	    });
	},
	/**
	 *  layui渲染自动加载页
	 */
	load: function(parentId) {
		var _that = this;
		_that.flow.load({
		    elem: '#dialog-img-group', //流加载容器
		    scrollElem: "#dialog-img-group",
		    isAuto: true,
		    isLazyimg: true,
		    done: function(page, next){ //加载下一页
		    	if (parentId == "0" || typeof parentId == 'undefined') {
		    		$(".upload-btn").hide();
		    	} else {
		    		$(".upload-btn").show();
		    	}
		    	var retObj = new Object();
		    	var params = {
		    		"param_parentId" : typeof parentId == 'undefined' ? "0" : parentId,
		    		"param_curpage" : page,
		    		"param_ipagecount" : 16,
		    		"param_type" : $(".param_type").val()
		    	};
		    	var res = "";
		    	Common.network(ctx + "/DocumentController/DialogPageList.do", "POST", params, false, function(data) {
		    		res = data;
		    	})
		    	//添加面包屑	
	    	    var breadcrumb = [];
	    		$(".layui-breadcrumb").empty();
		    	breadcrumb.push('<a href="javascript:void(0);" class="breadcrumb" file-id="0">根目录' + (res.parents == null ? "" : '<span class="layui-box">&gt;</span>') + '</a>');
	    		if (res.parents != null && res.parents.length > 0) {
			    	$.each(res.parents, function(i, o) {
			    	    if (i == res.parents.length - 1)
			    			breadcrumb.push('<a href="javascript:void(0);" file-id="' + o.fileId + '"><cite>' + o.fileName + '</cite></a>');
		    			else
		    				breadcrumb.push('<a href="javascript:void(0);" class="breadcrumb" file-id="' + o.fileId + '">' + o.fileName + '<span class="layui-box">&gt;</span></a>');
		    		});
	    		}
	    		$(".layui-breadcrumb").append(breadcrumb.join(""));
		    	//添加数据
		    	var lis = [];
		    	if (res.list != null && res.list.length > 0) {
			    	$.each(res.list, function(i, o) {
						var imgPath;
						if (o.fileType == "folder") {
							imgPath = ctx + "/images/icon/folder.png";
						} else if (o.fileType == "xlsx" || o.fileType == "xls") {
			    			imgPath = ctx + "/images/icon/excel.png";
			    		} else if (o.fileType == "doc" || o.fileType == "docx" || o.fileType == "dotx") {
			    			imgPath = ctx + "/images/icon/word.png";
			    		} else if (o.fileType == "pdf") {
			    			imgPath = ctx + "/images/icon/pdf.png";
			    		} else if (o.fileType == "ppt" || o.fileType == "pptx") {
			    			imgPath = ctx + "/images/icon/ppt.png";
			    		} else {
			    			imgPath = o.pathShow;
			    		}
			    		var content = "<div file-type='" + o.fileType + "' file-id='" + o.fileId + "' class='one-img'><img class='dialog-img-show' path='" + o.path + "' src='" + imgPath + "'/><span class='file-name'>" + o.fileName + "</span></div>";
			    		for (var index = 0; index < _that.chooseList.length; index++) {
			    			if (o.fileId == _that.chooseList[index].fileId) {
			    				content = "<div file-type='" + o.fileType + "' file-id='" + o.fileId + "' class='one-img' checked-img='true'><img class='dialog-img-show' path='" + o.path + "' src='" + imgPath + "'/><img class='checked-img-flag' src='" + path + "/images/page/checked.png'/><span class='file-name'>" + o.fileName + "</span></div>";
			    				break;
			    			}
			    		}
			    	    lis.push(content);
			    	});
		    	}
		    	next(lis.join(''), page < res.totalPage);
		    	_that.initEvent();
		    }
		});
	},
	/**
	 *  初始化事件
	 */
	initEvent: function() {
		var _that = this;
		var parentId = $(".layui-breadcrumb").find("a:last").attr("file-id");
	    //清除浮动
	    $(".clear-float").remove();
	    $(".one-img:last").after("<div class='clear-float' style='clear: both;'>");
	    //图片点击选中事件
	    $(".one-img").bind("click", function(i, o) {
			//是否是多选  0否  1是
	    	if ($(".choosemore").val() != "1") {
	    		_that.chooseList = [];
				//执行each代码  是单选
				$.each($(".one-img"), function(i, o) {
				    var $o = $(o);
				    if (typeof $o.attr("checked-img") != 'undefined' && $o.attr("checked-img") == "true") {
						$o.removeAttr("checked-img");
						$o.find(".checked-img-flag").remove();
				    }
				});
	    	}
		    var $that = $(this);
			//文件处理
			if ($that.attr("file-type") != "folder") {
				var temp = {}, isExist = false;
				temp.fileId = $that.attr("file-id");
				temp.path = $that.find("img").attr("path");
				temp.pathShow = $that.find("img").attr("src");
				temp.fileType = $that.attr("file-type");
				temp.fileName = $that.find("span.file-name").text();
				//如果存在相同则删除
				for (var index = 0; index < _that.chooseList.length; index++) {
					if (temp.fileId == _that.chooseList[index].fileId) {
						_that.chooseList.splice(index, 1);
						isExist = true;
					}
				}
				if (!isExist) {
					_that.chooseList.push(temp);
				}
			    if (typeof $that.attr("checked-img") != 'undefined' && $that.attr("checked-img") == "true") {
					$that.removeAttr("checked-img");
					$that.find(".checked-img-flag").remove();
					return false;
			    }
			    $that.attr("checked-img", "true").append('<img class="checked-img-flag" src="' + ctx + '/images/page/checked.png"/>');
			    return false;
			}
			/* 文件夹处理 */
			//清空
			$("#dialog-img-group").empty();
			//插入
			_that.load($that.attr("file-id"));
	    });
	    //面包屑点击事件
	    $(".breadcrumb").bind("click", function(i, o) {
			$("#dialog-img-group").empty();
			_that.load($(this).attr("file-id"));
	    });
	    //上传文件按钮点击事件
	    $(".upload-btn").unbind("click").bind("click", function() {
			_that.editFile(parentId);
	    });
	    //创建文件夹按钮点击事件
	    $(".create-folder-btn").unbind("click").bind("click", function() {
			_that.addFolder(parentId);
	    })
	}
};